<?php
/**
* 优惠券模块Api Service
*
* 优惠券模块Api Service的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Coupons;
use Input,Log;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\DataBase\SQL;
use App\Services\Tool\Coupons\CouponsTool;
use App\Services\Tool\Order\OrderTool;
use App\Services\UserService\UserTool;
use App\Services\Tool\Car\CarTool;

class CouponsService{
    function __construct(UserTool $userTool,
                         CarTool $carTool,
                         CouponsTool $couponsTool){
        $this->userTool    = $userTool;
        $this->carTool     = $carTool;
        $this->couponsTool = $couponsTool;
    }

    /**
        购物车优惠券列表
        参数：
            user_id         用户编号
            page            页码
            per_page        数据量
     */
    function shopCarCoupons($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
            !isset($input['per_page'])||
            !isset($input['page'])||
            !is_numeric($input['per_page'])||
            !is_numeric($input['per_page'])){
            return GeneralTool::createResult('','M00002');
        }
        if(empty($input['per_page'])){
            $input['per_page']  = 10;
        }else if($input['per_page']>50||$input['per_page']<1){
            $input['per_page']  = 50;
        }

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['time']  = time();
        //获取所有用户的所有可用优惠券
        $input['where'] = array('user_id'    => $input['user_id'],
                                'using_time' => 0,
                                'state'      => 1,
                                'type'       => 1);
        //获取渠道编号数组
        $channel_id = $this->couponsTool->get_my_coupon_channel_id_list($input['where']);

        $result     = $this->couponsTool->get_shop_car_can_use_from_channel($channel_id,$input['user_id']);

        $total      = $this->couponsTool->get_shop_car_total_fee($input,3);

        $coupons    = $this->couponsTool->get_shop_car_coupons_paginate($result,$input,$total);

        return GeneralTool::createResult($coupons,'M00000');
    }



    /**
        我的优惠券列表
        参数：
            user_id         用户编号
            type            类型 canUse可用 invalid已失效 used已使用
            page            页码
            per_page        每页数据量
     */
    function myCoupons($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
           !isset($input['per_page'])||!isset($input['page'])||
           !is_numeric($input['per_page'])||!is_numeric($input['per_page'])||
            !isset($input['type'])){
            return GeneralTool::createResult('','M00002');
        }
        if(empty($input['per_page'])){
            $input['per_page']  = 10;
        }else if($input['per_page']>50||$input['per_page']<1){
            $input['per_page']  = 50;
        }else{
            $input['per_page'] = ceil($input['per_page']);
        }

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $input['where'] = ['user_id'=>$input['user_id'],'state'=>1,'type'=>1];

        $coupons = $this->couponsTool->myCouponsList($input,'updated_at');

        return GeneralTool::createResult($coupons,'M00000');

    }

    /**
        立即购买用优惠券列表
        参数：
            user_id             用户编号
            product_id          商品编号
            quantity            数量
            page                页码
            per_page            每页显示数据量
     */
    function buyImmediatelyCoupons($input){
        //判断参数是否足够
        if(!isset($input['user_id'])||
           !isset($input['product_id'])||
           !isset($input['quantity'])||
           !isset($input['per_page'])||
           !isset($input['page'])||
           !is_numeric($input['page'])||
           !is_numeric($input['per_page'])){
            return GeneralTool::createResult('','M00002');
        }
        if(empty($input['per_page'])){
            $input['per_page']  = 10;
        }else if($input['per_page']>50||$input['per_page']<1){
            $input['per_page']  = 50;
        }


        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        if(empty($input['quantity'])||!is_numeric($input['quantity'])||$input['quantity']<=0)
            $input['quantity']  = 1;
        else
            $input['quantity']  = ceil($input['quantity']);

        $input['where'] = array('user_id'=>$input['user_id'],
                                'using_time'=>0,
                                'state'=>1,
                                'type'=>1);

        //获取渠道编号数组
        $channel_id = $this->couponsTool->get_my_coupon_channel_id_list($input['where']);

        $input['product_temp_id'] = $this->couponsTool->getTemplateByProductId($input['product_id']);
        $input['product_temp_id'] = isset($input['product_temp_id']) ? $input['product_temp_id'] : '';
        $input['total_postage']   = $this->couponsTool->get_postage_by_product_temp_id($input['product_temp_id']);
        $input['total_postage']   = isset($input['total_postage']) ? $input['total_postage'] : 0;

        $price      = $this->couponsTool->get_product_price($input['product_id']);

        if(!isset($price)) $price = 0;
        $input['total_fee'] = $price * $input['quantity'];

        //获取所有用户的所有可用优惠券
        $result  = $this->couponsTool->get_buy_now_can_use_from_channel($channel_id,$input);
        $input['total_fee'] += $input['total_postage'];
        $coupons = $this->couponsTool->get_shop_car_coupons_paginate($result,$input,$input['total_fee']);

        return GeneralTool::createResult($coupons,'M00000');
    }

    /**
        优惠券用户绑定
        参数：
            user_id     用户编号
            coupon_id   优惠券编号
     */
    function userUnionCoupons($input){
        if(!isset($input['user_id'])||!isset($input['coupon_id']))
            return GeneralTool::createResult('','M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        //判断优惠券是否可绑定
        $coupon = $this->couponsTool->getCouponInfo($input);

        if(!isset($coupon))
            return GeneralTool::createResult('','M05002');
        else if(isset($coupon->user_id)&&$coupon->user_id!='')
            return GeneralTool::createResult('','M05003');

        //判断优惠券类型

        //dd($coupon);

        if(!isset($coupon->binding_type)||
           !isset($coupon->code)||
           !isset($coupon->coupons))
            return GeneralTool::createResult('','M05004');

        try{

            if($coupon->binding_type==2){
                if($coupon->code!='00'||count($coupon->coupons)==0) return GeneralTool::createResult('','M05004');
                //大礼包
                $success = 0;
                foreach($coupon->coupons as $cou){
                    $re = SQL::update(['table'=>'coupons',
                                       'where'=>['coupon_id'=>$cou->coupon_id],
                                       'update'=>['user_id'=>$input['user_id'],'updated_at'=>time()]]);
                    if($re) $success++;
                }
                if($success != count($coupon->coupons)){
                    //绑定的优惠券数量不等于大礼包中优惠券数量
                    try{
                        throw new \Exception("绑定的优惠券数量不等于大礼包中优惠券数量");
                    }catch(\Exception $e){
                        Log::info($e);
                        Log::info($success);
                        Log::info($re);
                        SQL::CatchDo();
                        return GeneralTool::createResult('','M05004');
                    }
                }
                $result = SQL::update(['table'=>'coupons',
                                       'where'=>['coupon_id'=>$input['coupon_id']],
                                       'update'=>['user_id'=>$input['user_id']]]);
                return GeneralTool::createResult($coupon,'M00000');

            }else if($coupon->binding_type==1){
                if($coupon->code!='00') return GeneralTool::createResult('','M05012');
                //单券
                $result = SQL::update(['table'=>'coupons',
                                       'where'=>['coupon_id'=>$input['coupon_id']],
                                       'update'=>['user_id'=>$input['user_id'],'updated_at'=>time()]]);
                $param  = '{"coupon_id":"'.$input['coupon_id'].'","price":"'.(isset($coupon->price)?$coupon->price:'').'"}';

                $url    = asset('api/coupon/qrcode?body='.$param);

                $coupon = $this->couponsTool->getCouponInfo($input);
                //dd($coupon);
                if(isset($coupon)){
                    $coupon->url    = $url;
                }else{
                    $coupon         = (object)['url'=>$url];
                }

                return $result?GeneralTool::createResult($coupon,'M00000'):
                               GeneralTool::createResult('','M00001');

            }
            return GeneralTool::createResult('','M05004');
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return GeneralTool::createResult('','M00003');
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
       获取购物车优惠券详情
       参数：
           user_id         用户编号
           coupon_id       优惠券编号
     */
    function getCouponInfoByShopCar($input){
        if(!isset($input['user_id'])||!isset($input['coupon_id'])) return [];

        $channel_id = $this->couponsTool->get_coupon_channel_id_by_coupon_id(['user_id'    =>$input['user_id'],
                                                                              'coupon_id'  =>$input['coupon_id'],
                                                                              'using_time' =>0,
                                                                              'state'      =>1,
                                                                              'type'       =>1]);
        if(count($channel_id) == 0) return [];

        $result = $this->couponsTool->get_shop_car_can_use_from_channel($channel_id,$input['user_id']);

        $arr['coupon_id']  = $input['coupon_id'];
        $arr['channel_id'] = isset($result['channel_id']) && isset($result['channel_id'][0]) ? $result['channel_id'][0] : '';
        $arr['discount']   = isset($result['result']) && isset($result['result'][$arr['channel_id']]) ?
                             $result['result'][$arr['channel_id']] : '';
        $arr['coupon_price'] = $this->couponsTool->get_coupon_price($arr['coupon_id']);
        $arr['type']       = isset($result['result']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']['type'])?
                             $result['result'][$arr['channel_id'].'_detail']['type'] : '';
        $arr['reg_id']     = isset($result['result']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']['reg_id'])?
                             $result['result'][$arr['channel_id'].'_detail']['reg_id'] : '';

        return $arr;
    }

    /**
        获取立即购买优惠券详情
     */
    function getCouponInfoByBuyImmediately($input){
        if(!isset($input['user_id'])||!isset($input['coupon_id'])) return [];

        $channel_id = $this->couponsTool->get_coupon_channel_id_by_coupon_id(['user_id'    =>$input['user_id'],
                                                                              'coupon_id'  =>$input['coupon_id'],
                                                                              'using_time' =>0,
                                                                              'state'      =>1,
                                                                              'type'       =>1]);
        if(count($channel_id) == 0) return [];

        $result = $this->couponsTool->get_buy_now_can_use_from_channel($channel_id,$input);

        $arr['coupon_id']  = $input['coupon_id'];
        $arr['channel_id'] = isset($result['channel_id']) && isset($result['channel_id'][0]) ? $result['channel_id'][0] : '';
        $arr['discount']   = isset($result['result']) && isset($result['result'][$arr['channel_id']]) ?
                             $result['result'][$arr['channel_id']] : '';
        $arr['coupon_price'] = $this->couponsTool->get_coupon_price($arr['coupon_id']);
        $arr['type']       = isset($result['result']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']['type'])?
                             $result['result'][$arr['channel_id'].'_detail']['type'] : '';
        $arr['reg_id']     = isset($result['result']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']) &&
                             isset($result['result'][$arr['channel_id'].'_detail']['reg_id'])?
                             $result['result'][$arr['channel_id'].'_detail']['reg_id'] : '';

        return $arr;
    }

    /**
     * 优惠券券池发放
     * 参数：
     *     user_id          用户编号
     *     active_no        活动编号 微信摇一摇wx_shake201703
     *     code             兑奖编码
     */
    function coupon_pool_from_active($input){
        if(!isset($input['user_id']) ||
            !isset($input['active_no']) ||
            !isset($input['code']))
            return GeneralTool::createResult('', 'M00002');

        //判断用户是否存在
        if(!$this->userTool->isUser($input['user_id'])) return GeneralTool::createResult('','M05001');

        $active = CouponsTool::get_active_info(['active_no' => $input['active_no'], 'state' => 1]);
        if(!isset($active)) return GeneralTool::createResult('', 'M05068');

        //校验兑奖的合法性
        $verfy = CouponsTool::verfy_code($input);
        if($verfy['state'] != 'M00000') return $verfy;
        //发券
        $result = CouponsTool::coupon_pool_from_active(['user_id' => $input['user_id'], 'active' => $active]);
        if($result['state'] != 'M00000') return $result;
        if(!isset($result['result']['coupon_id'])) return  GeneralTool::createResult('', 'M00001');
        $bind   = $this->userUnionCoupons(['user_id' => $input['user_id'], 'coupon_id' => $result['result']['coupon_id']]);
        return $bind;
    }
}
